from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from content.models import Article, Category, Department, UserGroup, PermissionGroup, Permission, ArticleReview, CategoryReviewProcess
from custom_admin.widgets import ModalCategoryWidget

class AdminLoginForm(AuthenticationForm):
    username = forms.CharField(
        max_length=150, 
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '用户名'
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '密码'
        })
    )

class ArticleForm(forms.ModelForm):
    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects.all(),
        widget=ModalCategoryWidget(),
        required=True,
        label='分类'
    )
    
    class Meta:
        model = Article
        fields = ['title', 'content', 'published', 'categories']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'published': forms.CheckboxInput(attrs={'class': 'form-check-input'})
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.pk:
            # 通过ArticleCategory模型获取文章的分类
            self.fields['categories'].initial = Category.objects.filter(
                articlecategory__article=self.instance
            )

class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name', 'code', 'description', 'parent']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'code': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'parent': forms.Select(attrs={'class': 'form-control'})
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 排除自己作为父分类的选项
        if self.instance.pk:
            self.fields['parent'].queryset = Category.objects.exclude(
                pk=self.instance.pk
            )
        else:
            self.fields['parent'].queryset = Category.objects.all()
    
    def clean_code(self):
        code = self.cleaned_data['code']
        if not code:
            # 如果没有提供code，使用name生成
            name = self.cleaned_data.get('name', '')
            if name:
                base_code = name.replace(' ', '_').lower()
                code = base_code
                counter = 1
                while Category.objects.filter(code=code).exclude(pk=self.instance.pk).exists():
                    code = f"{base_code}_{counter}"
                    counter += 1
        return code
    
    def clean(self):
        cleaned_data = super().clean()
        parent = cleaned_data.get('parent')
        if self.instance.pk and parent:
            # 检查是否试图将分类设置为自己的子分类
            if parent.pk == self.instance.pk:
                raise forms.ValidationError('不能将分类设置为其自身的父分类')
            
            # 检查是否试图创建循环引用
            current = parent
            while current:
                if current.pk == self.instance.pk:
                    raise forms.ValidationError('不能将分类设置为自己的后代分类')
                current = current.parent
        return cleaned_data

# 部门表单
class DepartmentForm(forms.ModelForm):
    class Meta:
        model = Department
        fields = ['name', 'code', 'description', 'parent', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'code': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'parent': forms.Select(attrs={'class': 'form-control'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'})
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 排除自己作为父部门的选项
        if self.instance.pk:
            self.fields['parent'].queryset = Department.objects.exclude(
                pk=self.instance.pk
            ).exclude(
                parent=self.instance
            )
        else:
            self.fields['parent'].queryset = Department.objects.all()

# 用户组表单
class UserGroupForm(forms.ModelForm):
    class Meta:
        model = UserGroup
        fields = ['name', 'code', 'description', 'department', 'permission_groups', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'code': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'department': forms.Select(attrs={'class': 'form-control'}),
            'permission_groups': forms.SelectMultiple(attrs={'class': 'form-control'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'})
        }

# 权限组表单
class PermissionGroupForm(forms.ModelForm):
    class Meta:
        model = PermissionGroup
        fields = ['name', 'code', 'description', 'permissions', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'code': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'permissions': forms.SelectMultiple(attrs={'class': 'form-control'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'})
        }

# 权限表单
class PermissionForm(forms.ModelForm):
    class Meta:
        model = Permission
        fields = ['name', 'code', 'description', 'module']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'code': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'module': forms.TextInput(attrs={'class': 'form-control'}),
        }

# 审核表单
class ArticleReviewForm(forms.Form):
    ACTION_CHOICES = [
        ('approve', '通过'),
        ('reject', '拒绝')
    ]
    
    action = forms.ChoiceField(
        choices=ACTION_CHOICES,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    comment = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 3})
    )

# 栏目审核流程配置表单
class CategoryReviewProcessForm(forms.ModelForm):
    class Meta:
        model = CategoryReviewProcess
        fields = ['review_level', 'first_reviewer_group', 'final_reviewer_group', 
                  'auto_publish', 'notify_author', 'notify_reviewer', 'is_active']
        widgets = {
            'review_level': forms.Select(attrs={'class': 'form-control'}),
            'first_reviewer_group': forms.Select(attrs={'class': 'form-control'}),
            'final_reviewer_group': forms.Select(attrs={'class': 'form-control'}),
            'auto_publish': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'notify_author': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'notify_reviewer': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }